import React, {
  useCallback,
  useContext,
  useEffect,
  useImperativeHandle,
  useMemo,
  useReducer,
  useRef,
  useState
} from 'react'
import {
  Table, Button, Drawer, Form, Row, Col, Input, Select,
  DatePicker, List, Card, Empty, Tag, Checkbox, notification, Space
} from 'antd'
import { ProductStoreContext } from '@/views/productManagement/components/insideRework/index'
import { getQcReasonDetailList, getQcReasonList, getQcSolutionList } from '@/api/maintain'
import { getTechPageList } from '@/api/process'
import { ERR_OK } from '@/utils/commons'
import { CreateRework } from '@/api/rework'
import PhotoListSelect from '@/commonComp/photoListSelect'
import { rpd } from '@/views/productManagement/components/common'

const { Meta } = Card
const { Option } = Select

function RenderReworkReasonForm(props, ref) {
  // const formRef = useRef()
  const [form] = Form.useForm()
  const { submitCb } = props

  useImperativeHandle(ref, () => ({
    submit: () => {
      form.submit()
    }
  }))

  // const { state, dispatch } = useContext(ProductStoreContext)

  const [qReasonOpts, setQReasonOpts] = useState([])  //  不良原因大类
  const [qReasonDetailOpts, setQReasonDetailOpts] = useState([])  //  不良原因细类
  const [qSolutionOpts, setQSolutionOpts] = useState([])   //  解决办法
  const [techOpts, setTechOpts] = useState([]) // 返回工序

  useEffect(() => {
    (async() => {
      Array.of([setQReasonOpts, getQcReasonList],
        [setQReasonDetailOpts, getQcReasonDetailList],
        [setQSolutionOpts, getQcSolutionList]).map(async([set, req]) => {
        try {
          const { Result, Code } = await req()
          if (Code === ERR_OK) set(Result)
        } catch (e) {
          console.log(e)
        }
      })

      const { Result, Code } = await getTechPageList({ keyName: '', page: 1, pageSize: 99 })
      if (Code === ERR_OK) {
        const { Items } = Result
        setTechOpts(Items)
      }
    })()
  }, [])

  return <Form
    // fields={state.reworkReasonFrom}
    // onFieldsChange={(changedFields, allFields) => {
    //   dispatch({ type: 'reworkReasonFromChange', allFields, changedFields })
    // }}
    onFinish={values => void submitCb(values)}
    form={form}
    layout="vertical"
  >
    <Row gutter={16}>
      {/*<Col span={12}>*/}
      {/*  <Form.Item*/}
      {/*    name="name1"*/}
      {/*    label="不良现象"*/}
      {/*    rules={[{ required: true, message: 'Please enter user name' }]}*/}
      {/*  >*/}
      {/*    <Input/>*/}
      {/*  </Form.Item>*/}
      {/*</Col>*/}

      <Col span={12}>
        <Form.Item
          name="ReasonId"
          label="不良原因大类"
          rules={[{ required: true, message: 'Please select an ReasonId' }]}
        >
          <Select>
            {qReasonOpts.map(({ ReasonID, Description }) => {
              return <Option key={ReasonID} value={ReasonID}>{Description}</Option>
            })}
          </Select>
        </Form.Item>
      </Col>
      <Col span={12}>
        <Form.Item
          name="SolutionID"
          label="解决方式"
          rules={[{ required: true, message: 'Please select an SolutionID' }]}
        >
          <Select>
            {qSolutionOpts.map(({ SolutionID, Description }) => {
              return <Option key={SolutionID} value={SolutionID}>{Description}</Option>
            })}
          </Select>
        </Form.Item>
      </Col>
    </Row>
    <Row gutter={16}>
      <Col span={12}>
        <Form.Item
          name="ReasonDetailID"
          label="不良原因细类"
          rules={[{ required: true, message: 'Please select an ReasonDetailID' }]}
        >
          <Select>
            {qReasonDetailOpts.map(({ ReasonDetailID, Description }) => {
              return <Option key={ReasonDetailID} value={ReasonDetailID}>{Description}</Option>
            })}
          </Select>
        </Form.Item>
      </Col>
      <Col span={12}>
        <Form.Item
          name="ToTechId"
          label="返回工序"
        >
          <Select>
            {techOpts.map(({ TechId, Name }) => {
              return <Option key={TechId} value={TechId}>{Name}</Option>
            })}
          </Select>
        </Form.Item>
      </Col>
    </Row>
    {/*qSolutionOpts   Solution   */}
  </Form>
}

RenderReworkReasonForm = React.forwardRef(RenderReworkReasonForm)

const getValuesFromKeys = (object, arrKey) => {
  if (!Array.isArray(arrKey)) arrKey = Array.of(arrKey)
  return arrKey.map((k) => object[k], [])
}

const getCheckedPhotosByPartId = (state) => {
  //  state.selectPartId
  const { partsSelectPhotos, selectPartId } = state
  return partsSelectPhotos[selectPartId] || []
}

function RenderPhotoList() {
  const { state, dispatch } = useContext(ProductStoreContext)

  const photos = useMemo(() => {
    if (Object.keys(state.product).length === 0 || !state.selectPartId) {
      return Array.of()
    }
    const { fileIds } = state.product.partEntries[state.selectPartId]
    return getValuesFromKeys(state.product.fileEntries, fileIds)
  }, [state.product, state.selectPartId])

  const onChangeCheckPhotos = (photoIds) => {
    dispatch({ type: 'changePartsSelectPhotos', photoIds })
  }

  const checkedPhotos = useMemo(() => {
    return getCheckedPhotosByPartId(state)
  }, [state.partsSelectPhotos, state.selectPartId])

  return <PhotoListSelect {...{
    photos,
    checkedPhotos: checkedPhotos,
    onChangeCheckPhotos: ids => onChangeCheckPhotos(ids),
    imgSrcProp: 'CompressPath',
    renderCardDetail: rpd,
    pid:'OrderFileId'
  }}/>
}

//  照片列表
function RenderPhotoListDrawer() {
  const { state, dispatch } = useContext(ProductStoreContext)

  const handleCloseDrawer = (evt) => {
    dispatch({ type: 'compDetailDrawerToggle' })
  }
  // const getFilesByPartId = (state) => {
  //   console.log(state.product);
  //   console.log(state.selectPartId);
  const formRef = useRef()
  const [submitBtnLoading, setSubmitBtnLoading] = useState(false)

  const submitCb = (formValues) => {
    (async() => {
      try {
        const {
          product: { OrderProductId }, selectPartId: OrderProductPartID,
          partsSelectPhotos
        } = state
        //  不指定依赖的话,函数内部指向的还是旧版的state指针,但是state已经发生了改变,不再是原来的state指针了
        //  due to this closure trap trigger

        //  依赖指定的太多或者太少都不是好事
        //  太多(大),频繁重新运行,太少,引发bug

        setSubmitBtnLoading(true)
        //  call api
        const { Code } = await CreateRework(Array.of({
          OrderProductId, OrderProductPartID, ...formValues,
          ReworkFiles: getCheckedPhotosByPartId(state).map(OrderfileId => ({ OrderfileId }))
        }))

        if (Code === ERR_OK) {
          //  tips user success or error
          notification.success({ message: '提交返工申请成功.' })

          //  delete photos had submit from entries and partPhotoIds
          // dispatch({ type: 'removeCurSelectPhotos' })

          // todo setHasComplete

          //  delete current sel prodId
          // dispatch({ type: 'changePartsSelectPhotos', photoIds: [] })

          //  clear cur sel comp
          // dispatch({type:'changeCurrentComp',OrderProductPartId:-1})

          handleCloseDrawer()  //  close dialog
        }
      } catch (e) {
        console.log(e)
        notification.error({ message: '提交返工申请失败!' })
      } finally {
        setSubmitBtnLoading(false)
      }
    })()
  }

  return useMemo(() => <Drawer
    width={900}
    title="返工照片选择"
    placement={'right'}
    // closable={false}
    onClose={handleCloseDrawer}
    visible={state.drawerVisible}
    bodyStyle={{ paddingBottom: 80 }}
    footer={
      <div
        style={{
          textAlign: 'right'
        }}
      >
        <Button onClick={handleCloseDrawer} style={{ marginRight: 8 }}>
          取消
        </Button>
        <Button loading={submitBtnLoading} onClick={() => formRef.current['submit']()} type="primary">
          提交
        </Button>
      </div>
    }
  >
    {/* photo list */}
    <RenderPhotoList/>
    <RenderReworkReasonForm {...{ submitCb }} ref={formRef}/>
  </Drawer>, [state, dispatch])
}

// function photoModule() {
//
//   return <div>
//
//   </div>
// }

// export default photoModule

export default RenderPhotoListDrawer
